#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
验证 Live2D 库文件的完整性
"""

from pathlib import Path
import hashlib

def check_file(file_path, expected_min_size, expected_keywords):
    """检查文件是否存在且内容正确"""
    if not file_path.exists():
        return False, f"文件不存在: {file_path.name}"
    
    file_size = file_path.stat().st_size
    if file_size < expected_min_size:
        return False, f"文件太小 ({file_size} bytes < {expected_min_size} bytes)"
    
    # 检查文件内容
    try:
        with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
            content = f.read(1000)  # 读取前1000字符
            
            for keyword in expected_keywords:
                if keyword.lower() not in content.lower():
                    return False, f"缺少关键字: {keyword}"
        
        return True, f"✓ 验证通过 ({file_size:,} bytes)"
    
    except Exception as e:
        return False, f"读取失败: {e}"

def main():
    libs_dir = Path(__file__).parent / 'libs'
    
    print("=" * 70)
    print("Live2D 库文件完整性验证")
    print("=" * 70)
    
    # 定义需要验证的文件
    files_to_check = [
        {
            'name': 'PIXI.js',
            'filename': 'pixi.min.js',
            'min_size': 400000,  # 至少 400KB
            'keywords': ['PIXI', 'version']
        },
        {
            'name': 'Cubism 2 Runtime',
            'filename': 'live2d.min.js',
            'min_size': 100000,  # 至少 100KB
            'keywords': ['Live2D', 'function']
        },
        {
            'name': 'Cubism 4 Core',
            'filename': 'live2dcubismcore.min.js',
            'min_size': 150000,  # 至少 150KB
            'keywords': ['Live2DCubismCore', 'Version']
        },
        {
            'name': 'pixi-live2d-display (完整版)',
            'filename': 'pixi-live2d-display.min.js',
            'min_size': 100000,  # 至少 100KB
            'keywords': ['live2d', 'Live2DModel']
        },
    ]
    
    all_ok = True
    results = []
    
    for file_info in files_to_check:
        file_path = libs_dir / file_info['filename']
        is_ok, message = check_file(
            file_path,
            file_info['min_size'],
            file_info['keywords']
        )
        
        status = "✓" if is_ok else "✗"
        color = "32" if is_ok else "31"  # Green or Red
        
        print(f"\n{status} {file_info['name']}")
        print(f"  文件: {file_info['filename']}")
        print(f"  {message}")
        
        if not is_ok:
            all_ok = False
        
        results.append({
            'name': file_info['name'],
            'ok': is_ok,
            'message': message
        })
    
    print("\n" + "=" * 70)
    if all_ok:
        print("✓ 所有库文件验证通过!")
        print("\n您现在可以正常使用 Live2D 渲染系统了。")
    else:
        print("✗ 部分文件验证失败!")
        print("\n请运行以下脚本重新下载:")
        print("  python download_pixi_live2d.py")
        print("  python download_cubism2_runtime.py")
    print("=" * 70)

if __name__ == '__main__':
    main()
